package com.woniu.commons.interceptor;


import com.woniu.commons.anno.RequirePerms;
import com.woniu.commons.feign.FeignAuthService;
import com.woniu.commons.util.JWTUtil;
import com.woniu.commons.exception.UnAuthorizationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

//拦截器
@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Lazy //解决循环依赖问题,懒加载,在需要使用的时候才会创建对象
    @Resource
    private FeignAuthService feignAuthService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("拦截器执行了拦截");
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            //获取方法上的注解
            Method method = handlerMethod.getMethod();
            log.debug("方法名:{}", method.getName());
            if (method.isAnnotationPresent(RequirePerms.class)) {
                //获取注解的值
                RequirePerms requirePerms = method.getAnnotation(RequirePerms.class);
                //获取注解的值
                String perms = requirePerms.value();
                log.debug("注解的值:{}", perms);

                //判断用户是否拥有权限
                String token = request.getHeader("authorization");
                //通过用户id查询用户拥有的权限
                List<String> permsList = feignAuthService.findPerms(token).getData();

                if (!permsList.contains(perms)) {
                    //没有权限异常
                    throw new UnAuthorizationException("没有权限操作");
                }
            }
        }
        return true;
    }
}
